<?php 
namespace App\Http\Components;

use App\Http\Components\AppComponent;
use App\Models\AccountRecordsModel;
use App\Models\AlbumModel;
use App\Models\CorpsModel;
use App\Models\CorpsTeamModel;
use App\Models\FollowModel;
use App\Models\FriendModel;
use App\Models\LogUserBehaviorModel;
use App\Models\MatchDetailModel;
use App\Models\UserAccountModel;
use Illuminate\Http\Request;
use App\Models\UserModel;
use App\Models\UserProfileModel;
use App\library\UtilFunction;
use DB;
/**
* 
*/
class UserComponent extends AppComponent{
	
	public function __construct(){
        parent::__construct();
	}

    /*-------------------------------
        用户令牌token验证机制
    -------------------------------*/
    // 通过条件生成用户令牌
    public static function get_token($username,$app_login_time,$app_type){
        $token_arr = compact('username','app_login_time');
        ksort($token_arr);
        $app_token_data = implode("$app_type", $token_arr);
        $app_token = md5(md5(md5($app_token_data)));
        return $app_token;
    }

	// 通过请求数据判断token有效性
    public static function check_token(Request $request,$action = false){
        if (!intval($request->input('user_id'))) {
            return SELF::_json('301','用户未登录');
        }else{
            $user_id = $request->input('user_id');
        }
        if (!$request->input('debug')) {
            if (!$request->input('user_token')) {
                return SELF::_json('302','用户令牌不正确');
            }else{
                $user_token = $request->input('user_token');
            }
            if ($user = UserModel::where('user_id',$user_id)->first()) {
                $username = $user->phone;
                if($user->status == 3 &&  time()<$user->login_fobit_time){
                    $user->app_login_time = '';
                    $user->saveOrFail();
                }
                if (!$user->app_login_time) {
                    return SELF::_json('301','用户未登录');
                }
                $app_login_time = $user->app_login_time;
                $app_type = "$user->app_type";

                $api_token = SELF::get_token($username,$app_login_time,$app_type);
                if ($api_token == $user_token) {
                    if ($action) {
                        SELF::log($user_id,$action);
                    }
                    return $user->toArray();
                }else{
                    return SELF::_json('302','用户令牌已失效');
                }
            }else{
                return SELF::_json('303','登录用户编号不正确或已失效');
            }
        }
    }

    /**
     * 验证余额
     * account 账户信息
     * price 消费金额
     */
    public static function checkBalance($account,$price){
        if(round($account["balance"]-$account["frozen"],2)<round($price,2)){
            return SELF::_json('103','余额不足，请先充值');
        }
    }

    /**
     * @param $access_token
     * 验证2个人是否未好友
     */
    public static  function checkFriend($user_id1,$user_id2){
        $friend = FriendModel::where(function($query) use ($user_id1,$user_id2){
            $query->where('apply_user_id','=',$user_id1)
                ->where('agree_user_id','=',$user_id2)
                ->where("status",1);
        })->orwhere(function($query) use ($user_id1,$user_id2){
                $query->where('apply_user_id','=',$user_id2)
                    ->where('agree_user_id','=',$user_id1)
                    ->where("status",1);
        })->first();
        if($friend){
            return true;
        }else{
            return false;
        }
    }

    /**
     *获取用户相册
     * model=0普通相册  =1 私密照
     */
    public static function getAlbum($user_id,$model = -1){
        $result = array();
        if($model == -1){
           $album_list = AlbumModel::where("user_id",$user_id)->where("status",'!=',2)->get();
        }else{
           $album_list = AlbumModel::where("user_id",$user_id)->where("model",$model)->where("status",'!=',2)->get();
        }
        if($album_list){
            $album_list = $album_list->toArray();
            foreach($album_list AS $aitem){
                $temp = array(
                    "picture"=>UtilFunction::getUrlImg($aitem["picture"]),
                    "model"=>$aitem["model"]
                );
                $result[] = $temp;
            }
        }
        return $result;
    }

    /**
     * 验证是否已经关注
     */
    public static function check_follow($fans_user_id,$follow_user_id){
        $follow = FollowModel::where("fans_user_id",$fans_user_id)->where("follow_user_id",$follow_user_id)->first();
        if($follow){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 金额处理
     * model = 1  加钱
     * model=-1 减钱
     * price 永远大于等于0
     */
    public static  function price_save($source,$user_id,$price,$model,$payment_code = 'gold',$id = ""){
        $userAccount = UserAccountModel::where("user_id",$user_id)->first();
        $before_balance = $userAccount->balance;
        if($model == 1){
            //该用户的收入分 30% 给一级 20% 给 二级  10% 给三级
            if($source != 'master'){
                $userProfile = UserProfileModel::where("user_id",$user_id)->first()->toArray();
                if(!empty($userProfile)){
                    app()->configure('base');
                    $source_price = $price;
                    $level1_pre = config('base.level1');
                    $level2_pre = config('base.level2');
                    $level3_pre = config('base.level3');
                    if(!empty($userProfile["master_id"])){
                        $master_price = round($source_price/100*$level1_pre,2);
                        $price = $price-$master_price;
                        SELF::price_save('master',$userProfile["master_id"],$master_price,1,'gold',1);
                    }
                    if(!empty($userProfile["master_id2"])){
                        $master_price = round($source_price/100*$level2_pre,2);
                        $price = $price-$master_price;
                        SELF::price_save('master',$userProfile["master_id2"],$master_price,1,'gold',2);
                    }
                    if(!empty($userProfile["master_id3"])){
                        $master_price = round($source_price/100*$level3_pre,2);
                        $price = $price-$master_price;
                        SELF::price_save('master',$userProfile["master_id3"],$master_price,1,'gold',3);
                    }
                }
            }


            $userAccount->balance = ($userAccount->balance+$price);
            $userAccount->income = ($userAccount->income+$price);
            $userAccount->today_income = ($userAccount->today_income+$price);

        }elseif($model == -1){
            $userAccount->balance = ($userAccount->balance-$price);
            $userAccount->spending = ($userAccount->spending+$price);
        }else{
            return ;
        }
        $accountRecords = new AccountRecordsModel();
        $accountRecords->user_id = $user_id;
        $accountRecords->price = ($model == 1)?$price:-$price;
        $accountRecords->before_balance = $before_balance;
        $accountRecords->payment_code = $payment_code;
        switch($source){
            case 'video_chat':
                $accountRecords->source = 2;
                $accountRecords->source_remark = "视频聊天";
                $accountRecords->video_chat_id = $id;
                $userAccount->saveOrFail();
                $accountRecords->saveOrFail();
                break;
            case 'buy_card':
                $accountRecords->source = 3;
                $accountRecords->source_remark = "购买会员";
                $userAccount->saveOrFail();
                $accountRecords->saveOrFail();
                break;
            case 'flower':
                $accountRecords->source = 4;
                $accountRecords->source_remark = "送花";
                $userAccount->saveOrFail();
                $accountRecords->saveOrFail();
                break;
            case 'see_wechat':
                $accountRecords->source = 5;
                $accountRecords->source_remark = "查看微信号";
                if($model == 1){
                    $userAccount->wechat_income = $userAccount->wechat_income+$price;
                }

                $userAccount->saveOrFail();
                $accountRecords->saveOrFail();
                break;
            case 'job_order':
                $accountRecords->source = 6;
                $accountRecords->source_remark = "订单付款";
                $accountRecords->order_id = $id;
                if($model == -1){
                    $userAccount->frozen = $userAccount->frozen-$price;
                }
                $userAccount->saveOrFail();
                $accountRecords->saveOrFail();
                break;
            case 'gift':
                $accountRecords->source = 7;
                $accountRecords->source_remark = "送礼物";
                $accountRecords->user_gift_id = $id;
                $userAccount->saveOrFail();
                $accountRecords->saveOrFail();
                break;
            case 'master':  //分销收入
                $accountRecords->source = 8;
                $accountRecords->source_remark = "推广收入";
                $accountRecords->master_level = $id;
                $accountRecords->saveOrFail();
                switch($id){
                    case 1:
                        $userAccount->master1_income = $userAccount->master1_income+$price;
                        break;
                    case 2:
                        $userAccount->master2_income = $userAccount->master2_income+$price;
                        break;
                    case 3:
                        $userAccount->master3_income = $userAccount->master3_income+$price;
                        break;
                }
                $userAccount->master_income = $userAccount->master_income+$price;
                $userAccount->saveOrFail();

                break;
            case 'safety':  //保安员收入
                $accountRecords->source = 11;
                $accountRecords->source_remark = "保安员收入";
                $accountRecords->order_id = $id;
                $userAccount->saveOrFail();
                $accountRecords->saveOrFail();
                break;
            case 'agent':  //代理商收入
                $accountRecords->source = 9;
                $accountRecords->source_remark = "代理商收入";
                $accountRecords->order_id = $id;
                $userAccount->agent_income = $userAccount->agent_income+$price;
                $userAccount->saveOrFail();
                $accountRecords->saveOrFail();
                break;
        }
    }



    /*获取第三方登录授权信息*/
    public static function get_auth_info($access_token,$openid,$auth_type = 'wechat',$app_type = 'ios'){
        // $access_token = 'OezXcEiiBSKSxW0eoylIeOpXBAk4Kpfsry-J3TpcYpEPIVQbckRt8pE1PlYOW35h6mM0Y6AaJr6i0Q1SFCnZUAdWhpAgpIgcoOUTiLzR1iKohCKOFNMNUcvAdDOROStsY4JzzcN-EYVhpbQQnzUlJA';
        // $openid = 'os-wJt11IMcfA_QL-MqC3uBgsG78';
        if ($auth_type == 'wechat') {
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid;
            $auth_info = file_get_contents($url);
            if ($info_arr = json_decode($auth_info,true)) {
                if (isset($info_arr['errcode'])) {
                    $errmsg = $info_arr['errmsg'];
                }
                return $info_arr;
            }else{
                return false;
            }
        }else{
            app()->configure('account');
            if ($app_type == 'ios') {
                $oauth_consumer_key = config('account.qq_ios_oauth_consumer_key');
            }
            if ($app_type == 'android') {
                $oauth_consumer_key = config('account.qq_android_oauth_consumer_key');
            }
            $url = 'https://graph.qq.com/user/get_simple_userinfo?access_token='.$access_token.'&oauth_consumer_key='.$oauth_consumer_key.'&openid='.$openid;
            $auth_info = file_get_contents($url);
            if ($info_arr = json_decode($auth_info,true)) {
                if (isset($info_arr['ret']) && $info_arr['ret'] != 0) {
                    $return_arr['errcode'] = $info_arr['ret'];
                    $return_arr['errmsg'] = $info_arr['msg'];
                }
                $return_arr['nickname'] = $info_arr['nickname'];
                $return_arr['headimgurl'] = $info_arr['figureurl_qq_2']?$info_arr['figureurl_qq_2']:$info_arr['figureurl_qq_1'];
                $return_arr['sex'] = $info_arr['gender'] == '男'?1:2;
                return $return_arr;
            }else{
                return false;
            }
        }
    }



}
